<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            width: 200px;
            height: 50px;
            background-color: grey;
            position: relative;
            border-radius: 50px;
            overflow: hidden;
        }

        p {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: aqua;
            position: absolute;
            z-index: 10;
            -webkit-user-select: none;
        }

        h4 {
            width: 175px;
            height: 50px;
            position: absolute;
            left: -150px;
            background-color: green;
        }
    </style>
</head>

<body>
    <div>
        <P></P>
        <h4></h4>
    </div>
    <script>
        const oDiv = document.querySelector('div');
        const oP = document.querySelector('P');
        const oH4 = document.querySelector('h4');
        const w = oDiv.clientWidth - oP.offsetWidth;

        let turn = true;
        let flag = true ;
        let n = 0;

        //创建点击
        oP.onclick = function () {
            if(turn&&flag){
                flag = false ;
                const t = setInterval(() => {
                n += 10;
                oP.style.left = n + 'px';
                oH4.style.left = -w + n + 'px';

                //判断什么时候结束
                if (n >= w) {
                    n = w;
                    oP.style.left = n + 'px';
                    oH4.style.left = -w + n + 'px';
                    clearInterval(t);
                    oP.style.backgroundColor = 'yellow' ;
                    turn = false ;
                    flag = true ;
                }
            }, 20)
            }
            else if(turn === false && flag){
                flag = false ;
                const t = setInterval(() => {
                
                n -= 10;
                oP.style.left = n + 'px';
                oH4.style.left = -w + n + 'px';

                //判断什么时候结束
                if (n <= 0) {
                    n = 0;
                    oP.style.left = n + 'px';
                    oH4.style.left = -w + n + 'px';
                    clearInterval(t);
                    oP.style.backgroundColor = 'aqua' ;
                    turn = true ;
                    flag = true ;
                }
            }, 20)
            
            }

        }

    </script>

</body>

</html>